<template>
  <el-dialog
    :title="!dataForm.brandId ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
    :before-close="beforeClose"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      label-width="140px"
    >
      <el-form-item label="品牌名" prop="name">
        <el-input v-model="dataForm.name" placeholder="品牌名"></el-input>
      </el-form-item>
      <el-form-item label="品牌logo" prop="logo">
        <el-upload
          class="upload-demo"
          action="#"
          :before-upload="checkFileSize"
          :limit="1"
          :http-request="upload"
          :file-list="fileList"
          list-type="picture">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过10Mb</div>
        </el-upload>
      </el-form-item>
      <el-form-item label="介绍" prop="descript">
        <el-input v-model="dataForm.descript" placeholder="介绍"></el-input>
      </el-form-item>
      <el-form-item label="显示" prop="showStatus">
        <el-switch
          v-model="dataForm.showStatus"
          :active-value="1"
          :inactive-value="0"
          active-color="#13ce66"
          inactive-color="#ff4949">
        </el-switch>
        {{dataForm.showStatus}}
      </el-form-item>
      <el-form-item label="检索首字母" prop="firstLetter">
        <el-input
          v-model="dataForm.firstLetter"
          placeholder="检索首字母"
        ></el-input>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="dataForm.sort" controls-position="right" :min="0" :max="10"></el-input-number>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { brandInfo, saveBrand, updateBrand } from "@/api/product/product.js";
import { upload } from "@/api/common.js"
export default {
  data() {
    return {
      fileList: [], // 用于更新时回显logo
      files: [], // 用于添加时给logo赋值
      visible: false,
      dataForm: {
        brandId: 0,
        name: "",
        logo: "",
        descript: "",
        showStatus: "",
        firstLetter: "",
        sort: "0",
      },
      dataRule: {
        name: [{ required: true, message: "品牌名不能为空", trigger: "blur" }],
        firstLetter: [
          { required: true, message: "检索首字母不能为空", trigger: "blur" },
          { min: 1, max: 1, message: "最长一个字符" }
        ],
      },
    };
  },
  methods: {
    init(id) {
      this.fileList = [];
      this.files = [];
      this.dataForm.brandId = id || 0;
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        if (this.dataForm.brandId) {
          brandInfo(this.dataForm.brandId).then((data) => {
            if (data && data.code === 0) {
              this.dataForm.name = data.brand.name;
              this.dataForm.logo = data.brand.logo;
              this.dataForm.descript = data.brand.descript;
              this.dataForm.showStatus = data.brand.showStatus;
              this.dataForm.firstLetter = data.brand.firstLetter;
              this.dataForm.sort = data.brand.sort;
              this.fileList.push({name: data.brand.logo.split('/')[-1], url: data.brand.logo})
            }
          });
        }
      });
    },
    // 模态框关闭之前
    beforeClose(done){
      this.fileList = [];
      this.dataForm = {
        brandId: 0,
        name: "",
        logo: "",
        descript: "",
        showStatus: "",
        firstLetter: "",
        sort: "0",
      };
      this.files = [];
      done();
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          const data = {
            brandId: this.dataForm.brandId || undefined,
            name: this.dataForm.name,
            logo: this.files[0] == null ? undefined : this.files[0].url,
            descript: this.dataForm.descript,
            showStatus: this.dataForm.showStatus==true?1:0,
            firstLetter: this.dataForm.firstLetter,
            sort: this.dataForm.sort,
          };

          if (!this.dataForm.brandId) {
            saveBrand(data).then((data) => {
              if (data && data.code === 0) {
                this.$message({
                  message: "操作成功",
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.visible = false;
                    this.$emit("refreshDataList");
                  },
                });
              } else {
                this.$message.error(data.msg);
              }
            });
          } else {
            updateBrand(data).then((data) => {
              if (data && data.code === 0) {
                this.$message({
                  message: "操作成功",
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.visible = false;
                    this.$emit("refreshDataList");
                  },
                });
              } else {
                this.$message.error(data.msg);
              }
            });
          }
        }
      });
    },
    // 检查上传文件大小
    checkFileSize(file){
      if(file.size > 1024*1024*10){
        this.$message({
          type: 'warning',
          message: '图片过大'
        })
        return false;
      }
      return true;
    },

// 图片上传
    upload(file){
      let formData = new FormData();
      formData.append("file", file.file);
      upload(formData)
      .then((res)=>{
        if(res.code==0){
          this.files.push({name: file.file.name, url: res.url})
        }
      }).catch((err)=>{console.log(err)})
    },

    fileRemove(file, fileList){
      console.log(file, fileList)
    }
  },
};
</script>
